import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View, Image, Text, Block, ScrollView, Button} from '@tarojs/components'
import {AtButton, AtIcon, AtInput, AtModal, AtModalAction, AtModalHeader} from 'taro-ui'
import {platform} from '../../../utils/platform-settting.service'
import {PlatformSet} from '../../../utils/server.interface'
import {user} from '../../../utils/user.service'
import {http} from '../../../utils/http'
import {
  BECOME_CONTENT,
  GET_PHONE,
  REGISTER_SELLER,
  REGISTER_TOP_SELLER, SELLER_CONTENT, TARO_ENV
} from '../../../constants/api'
import {GetRequest, throttle, vcmonitor} from "../../../utils/tools";
import {h5Wx} from "../../../utils/h5.service";
import GzhAuth from "../../../components/gzh-auth/gzh-auth"
import {getContent} from "../../../utils/handlerPublicCode";
import './join.scss'

interface formData {
  sid?: number
  parent_seller_id?: number
  source_user_id?: number
  poster_name: string
  real_name: string
  phone: string
  slogan: string
  company: string
  area: string[]
  address: string
  delivery_province: string
  delivery_city: string
  delivery_area: string
}

interface LoginParamType {
  nickName: string
  gender: number
  language: string
  city: string
  province: string
  country: string
  avatarUrl: string
  bindSellerId: number
  itemUUID: string
  path: string
}

interface ServerPhone {
  phoneNumber: string
  purePhoneNumber: string
  countryCode: string
  watermark: {
    timestamp: number
    appid: string
  }
}

export default class Index extends Component {
  state: {
    showInputUserInfoDialog: boolean
    userName: any
    userPhone: any
    sellerStatus: any
    shequn: boolean
    imgUrl: string
    becomeContent: any
    minHeight: any
    platformInfo: PlatformSet | false
    submitting: boolean
    formData: formData
    loginParam: LoginParamType
    joinurl: string
    loading: any
    showFloat: any
    developContent: any
    from: any
    showDialog: any
    alreadySeller: boolean
  } = {
    alreadySeller: false,
    showInputUserInfoDialog: false,
    userName: '',
    userPhone: '',
    sellerStatus: 0,
    developContent: false,
    showFloat: false,
    becomeContent: false,
    loading: true,
    shequn: false,
    imgUrl: 'https://resource.ivcheng.com/resources/images/join.png',
    platformInfo: false,
    submitting: false,
    formData: {
      poster_name: '',
      real_name: '',
      phone: '',
      slogan: '',
      company: '',
      area: [],
      address: '',
      delivery_province: '',
      delivery_city: '',
      delivery_area: '',
    },
    minHeight: 0,
    loginParam: {
      nickName: '',
      gender: 1,
      language: '',
      city: '',
      province: '',
      country: '',
      avatarUrl: '',
      bindSellerId: 0,
      itemUUID: '',
      path: '',
    },
    from: '',
    joinurl: ''
  }

  async UNSAFE_componentWillMount() {
    vcmonitor(this)
    const {sellerId = '', sid = '', sourceUserId = '', from = '', showDialog = '', siteId = ''} = Taro.getCurrentInstance().router.params
    if (!from && process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
      const shareData = {
        title: platform.info.platformName,
        desc: '注册成为分销商',
        link: window.location.origin + '/common/distributor/invite/join',
        imgUrl: platform.info.platformLogo
      };
      await h5Wx.share(shareData);
    }
    if (!from) {
      const userIdentity = await user.getUserData()
      if (userIdentity && userIdentity.isSeller) {
        Taro.showToast({title: '您已成为分销商！'})
        this.setState({alreadySeller: true})
        const timer = setTimeout(() => {
          clearTimeout(timer)
          Taro.switchTab({url: '/pages/index/index'})
        }, 1500)
        return
      }
      if (userIdentity && userIdentity.sellerStatus && userIdentity.sellerStatus === 3) {
        Taro.redirectTo({url: '/common/distributor/invite/group'})
        return false
      }
    }
    let platformSet = platform.info
    if (!platform.isLoaded) {
      platformSet = (await platform.getSetting()) || platform.info
    }
    let developContent
    let becomeContent
    if (from) {
      developContent = await http.carGet(SELLER_CONTENT, {sid: siteId})
      becomeContent = await http.carGet(BECOME_CONTENT, {sid: siteId})
    } else {
      developContent = await http.carGet(SELLER_CONTENT, {})
      becomeContent = await http.carGet(BECOME_CONTENT, {})
    }
    this.setState({
      platformInfo: platformSet,
      developContent: developContent.content || '',
      becomeContent: becomeContent.content || '',
      loading: false
    })
    this.setState({from, showFloat: !!showDialog})
    const formData = this.state.formData
    const joinurl = sellerId ? REGISTER_SELLER : REGISTER_TOP_SELLER
    Taro.getSystemInfo({
      success: (res) => {
        this.setState({minHeight: res.windowHeight / 2 - 60})
      }
    })
    if (from) {
      return
    }
    if (sellerId) {
      formData['parent_seller_id'] = parseInt(sellerId)
      Taro.setStorageSync('bindSellerId', formData['parent_seller_id'])
    }
    if (sid) {
      formData['sid'] = parseInt(sid)
      Taro.setStorageSync('sid', formData['sid'])
    } else {
      const sid2 = Taro.getStorageSync('sid') || ''
      if (sid2) formData['sid'] = parseInt(sid2)
    }
    if (sourceUserId) {
      formData['source_user_id'] = parseInt(sourceUserId)
      Taro.setStorageSync('sourceUserId', formData['source_user_id'])
    } else {
      if (Taro.getStorageSync('sourceUserId')) {
        formData['source_user_id'] = Taro.getStorageSync('sourceUserId')
      }
    }
    this.setState({formData, joinurl})
  }

  async componentDidShow() {
    const {from = ''} = Taro.getCurrentInstance().router.params
    if (!from && !(await user.checkLogin())) {
      await user.jumpLogin()
    }
  }

  getToken(num) {
    const res = Taro.getStorageSync("user")
    if (num < 10) {
      if (res.token) {
        return true
      } else {
        return this.getToken(num++)
      }
    } else {
      return false
    }
  }

  async inputUserInfo() {
    this.setState({showInputUserInfoDialog: true, userName: '', userPhone: ''})
  }

  handleChange(name, value) {
    this.setState({[name]: value});
  }

  setStateSync(state) {
    return new Promise(resolve => {
      this.setState(state, resolve);
    });
  }

  isShowFloat() {
    this.setState({submitting: false})
    if (!this.state.developContent) {
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/index/index'})
      }, 1500)
    } else {
      this.setState({showFloat: true})
    }
  }

  async getStatus(data) {
    const res = await http.post<ServerPhone>(GET_PHONE, {
      encryptedData: data[0].detail.encryptedData,
      iv: data[0].detail.iv
    })
    if (res) {
      const formData = this.state.formData
      formData['phone'] = res.phoneNumber || ''
      const ret = await http.post(this.state.joinurl, {...formData})
      if (ret) {
        this.setState({sellerStatus: ret.status, submitting: false})
        if (ret.status == 1) {
          Taro.showToast({title: '注册成功！'})
          await user.setUserData()
          this.isShowFloat()
        } else if (ret.status == 3) {
          if (this.state.becomeContent) {
            this.setState({showFloat: true})
          } else {
            Taro.redirectTo({url: '/common/distributor/invite/group'})
          }
        }
      } else {
        this.isShowFloat()
      }
    } else {
      this.setState({submitting: false})
    }
  }

  async getPhoneNumber(data) {
    const name = this.state.userName
    const userPhone = this.state.userPhone
    if (!name) {
      Taro.showToast({title: '请填写姓名', icon: 'none'})
      return
    }
    if (process.env.TARO_ENV !== 'h5') {
      this.setState({showInputUserInfoDialog: false})
    }
    const formData = this.state.formData
    formData['real_name'] = name
    await this.setStateSync({formData});
    if (process.env.TARO_ENV === 'h5') {
      if (!userPhone) {
        Taro.showToast({title: '请填写手机号', icon: 'none'})
        return
      }
      formData['phone'] = userPhone
      await this.setStateSync({formData});
      const ret = await http.post(this.state.joinurl, {...formData})
      if (!ret) {
        return
      }
      this.setState({showInputUserInfoDialog: false, sellerStatus: ret.status, submitting: false})
      if (ret.status === 1) {
        Taro.showToast({title: '注册成功！'})
        await user.setUserData()
        this.isShowFloat()
      } else if (ret.status === 3) {
        if (this.state.becomeContent) {
          this.setState({showFloat: true})
        } else {
          Taro.redirectTo({url: '/common/distributor/invite/group'})
        }
      } else {
        this.isShowFloat()
      }
    } else {
      this.setState({showInputUserInfoDialog: false, submitting: true})
      await this.getStatus(data)
    }
  }

  inputBlur() {
    if (TARO_ENV === 'h5') {
      window.scrollTo(0, 0);
    }
  }

  render() {
    const {sellerStatus, alreadySeller, showInputUserInfoDialog, userName, userPhone, from, minHeight, showFloat, becomeContent, loading, developContent, platformInfo, submitting, imgUrl, shequn} = this.state
    return (
      <View className='join-us'>
        <GzhAuth />
        {!alreadySeller && !loading && <Block>
          {!developContent && <View>
            <View className='welcome'>欢迎您成为我们的分享{process.env.fxName}</View>
            <View className='img-box'>
              <Image className='img' src={imgUrl} mode='aspectFit' />
            </View>
            <View className='slogan-box'>
              <View className='item'>自用<Text className='slogan'>省钱</Text></View>
              <View className='item'>分享<Text className='slogan'>赚钱</Text></View>
            </View>
          </View>}
          {from !== 'pc' && <View className={`btn-box ${developContent && 'btn-box-fixed'}`}>
            <AtButton onClick={throttle(this.inputUserInfo.bind(this), 1000)} disabled={submitting}
              loading={submitting} type='primary'
            >立即成为分享{process.env.fxName}</AtButton>
          </View>}
          {platformInfo && platformInfo.platformName && !developContent &&
          <View className='platform-name'>{platformInfo.platformName}</View>}
          {developContent && <Block>
            {process.env.TARO_ENV === "weapp" && <parser selectable html={developContent || ''} />}
            {process.env.TARO_ENV === "tt" && <rich-text preview selectable nodes={getContent(developContent)} />}
            {process.env.TARO_ENV === "h5" &&
            <View id='html-description' dangerouslySetInnerHTML={{__html: developContent}} />}
            <View className='customData-height' />
          </Block>}
        </Block>}
        {!alreadySeller && showInputUserInfoDialog &&
        <AtModal className='model' isOpened={showInputUserInfoDialog} onClose={() => {
          this.setState({showInputUserInfoDialog: false})
        }}
        >
          <AtModalHeader><AtIcon onClick={() => {
            this.setState({showInputUserInfoDialog: false})
          }} className='close-cla' value='close' size='20' color='#888888'
          /></AtModalHeader>
          <View className='w-b-ba'>
            <AtInput
              maxLength='12'
              name='value'
              title='姓名'
              type='text'
              className='inputUserInfo'
              required
              placeholder='请输入姓名'
              value={userName}
              onBlur={this.inputBlur.bind(this)}
              onChange={this.handleChange.bind(this, 'userName')}
            />
            {process.env.TARO_ENV == 'h5' && <AtInput
              name='value'
              title='手机号'
              type='phone'
              className='inputUserInfo'
              required
              placeholder='请输入手机号'
              value={userPhone}
              onBlur={this.inputBlur.bind(this)}
              onChange={this.handleChange.bind(this, 'userPhone')}
            />}
          </View>
          <AtModalAction>
            {process.env.TARO_ENV == 'weapp' && <AtButton disabled={submitting} loading={submitting} openType='getPhoneNumber' onGetPhoneNumber={throttle(this.getPhoneNumber.bind(this), 1000)} type='primary' className='readed'>确定</AtButton>}
            {process.env.TARO_ENV == 'h5' && <AtButton disabled={submitting} loading={submitting}
              onClick={throttle(this.getPhoneNumber.bind(this), 1000)}
              type='primary' className='readed'
            >确定</AtButton>}</AtModalAction>
        </AtModal>}
        {!alreadySeller && showFloat && <AtModal className='model' isOpened={showFloat} onClose={() => {
          this.setState({showFloat: false})
        }}
        >
          <AtModalHeader><AtIcon onClick={() => {
            this.setState({showFloat: false})
          }} className='close-cla' value='close' size='20' color='#888888'
          /></AtModalHeader>
          <View className='w-b-ba'>
            <ScrollView
              style={`min-height:${minHeight + 'px'};max-height:${minHeight + 'px'}`}
              className='scrollView'
              scrollY
            >
              {process.env.TARO_ENV === "weapp" && <parser selectable html={becomeContent || ''} />}
              {process.env.TARO_ENV === "tt" && <rich-text preview selectable nodes={getContent(becomeContent)} />}
              {process.env.TARO_ENV === "h5" && !!becomeContent &&
              <View dangerouslySetInnerHTML={{__html: becomeContent}} />}
            </ScrollView>
          </View>
          <AtModalAction><Button onClick={() => {
            this.setState({showFloat: false})
            if (sellerStatus == 3) {
              Taro.redirectTo({url: '/common/distributor/invite/group'})
            }
          }} className='readed'
          >确定</Button></AtModalAction>
        </AtModal>}
      </View>
    )
  }
}
